package com.alex.boot.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.PropertySources;
import org.springframework.core.io.ClassPathResource;

import javax.annotation.PostConstruct;

/**
 * 获取yml文件数据.
 */
@Configuration
public class LoadYamlFileConfig {

    @Autowired
    private PropertySourcesPlaceholderConfigurer configurer;

    // 加载YML格式自定义配置文件
    @Bean
    public static PropertySourcesPlaceholderConfigurer properties() {
        PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
        YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
//        yaml.setResources(new FileSystemResource("config.yml"));//File引入
        yaml.setResources(new ClassPathResource("my-data.yml"));//class引入
        configurer.setProperties(yaml.getObject());
        return configurer;
    }

    @PostConstruct
    public void post() {
        PropertySources propertySources = configurer.getAppliedPropertySources();
        propertySources.stream().forEach(item -> {
            // 分为localProperties 和 environmentProperties
            /**
             * environmentProperties中可以获取的数据
             * 1. jdk的一些信息
             * 2. PID
             * 3. 虚拟机相关信息
             * 4. 当前计算机登录用户信息
             * 5. 当前计算机的一些信息
             * 6. 获取配置文件中配置的所有数据(application.yml).
             */
            if (item.getName().equals("localProperties")) {
                Object userName = item.getProperty("user.name");
                System.out.println("--->" + userName);
            }
        });
    }
}
